package com.whli.jee.system.service.impl;

import com.whli.jee.common.exception.BusinessException;
import com.whli.jee.common.util.*;
import com.whli.jee.common.web.dao.IBaseDao;
import com.whli.jee.common.web.service.impl.BaseServiceImpl;
import com.whli.jee.system.dao.ISysUserDao;
import com.whli.jee.system.entity.SysUser;
import com.whli.jee.system.entity.SysUserRole;
import com.whli.jee.system.service.ISysRoleService;
import com.whli.jee.system.service.ISysUserRoleService;
import com.whli.jee.system.service.ISysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author whli
 * @version 1.0
 * @since 1.0
 */
@Service(value = "sysUserService")
public class SysUserServiceImpl extends BaseServiceImpl<SysUser> implements ISysUserService {

    @Autowired
    private ISysUserDao sysUserDao;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysRoleService sysRoleService;

    @Override
    public IBaseDao<SysUser> getDao() {
        return sysUserDao;
    }

    @Override
    public int save(SysUser entity) {
        if (StringUtils.isBlank(entity.getLoginName())){
            throw new BusinessException("用户名不能为空！");
        }

        SysUser temp = getByLoginNameOrEmailOrPhone(entity.getLoginName());
        if (BeanUtils.isNotNull(temp)) {
            throw new BusinessException("【"+entity.getLoginName()+"】该用户已存在！");
        }

        entity.setEnable("1");
        entity.setPassword(PwdUtils.md5Encode("123456", entity.getLoginName()));
        int rows = super.save(entity);
        //设置默认角色USER
        SysUserRole userRole = new SysUserRole();
        userRole.setRoleId("2");
        userRole.setUserId(entity.getId());
        sysUserRoleService.save(userRole);

        return rows;
    }


    @Override
    public int delete(String id) {
        if (StringUtils.isBlank(id)){
            throw new BusinessException("修改数据不能为空！");
        }
        SysUser user = sysUserDao.getByPK(id);
        user.setEnable("0");
        return sysUserDao.update(user);
    }

    @Override
    public int deleteBatch(List<String> ids) {
        if (ids == null || CollectionUtils.isEmpty(ids)){
            throw new BusinessException("修改数据不能为空！");
        }
        List<SysUser> users = sysUserDao.listByPKs(ids);
        for (SysUser user : users){
            user.setEnable("0");
        }
        return updateBatch(users);
    }

    /**
     * 根据登录名检查用户是否存在
     *
     * @param loginName
     * @return
     */
    @Override
    public SysUser getByLoginNameOrEmailOrPhone(String loginName) {
        SysUser currentUser = null;
        if (StringUtils.isNotBlank(loginName)) {
            currentUser = sysUserDao.getByLoginNameOrEmailOrPhone(loginName);
        }
        return currentUser;
    }

    @Override
    public SysUser getByEmail(String email) {
        if(StringUtils.isBlank(email)){
            throw new BusinessException("请选择需要查询的数据！");
        }
        SysUser entity = sysUserDao.getByEmail(email);
        if(BeanUtils.isNull(entity)){
            throw  new BusinessException("查询的数据不存在或已删除！");
        }
        return entity;
    }

    @Override
    public SysUser getByPhone(String phone) {
        if(StringUtils.isBlank(phone)){
            throw new BusinessException("请选择需要查询的数据！");
        }
        SysUser entity = sysUserDao.getByPhone(phone);
        if(BeanUtils.isNull(entity)){
            throw  new BusinessException("查询的数据不存在或已删除！");
        }
        return entity;
    }

    @Override
    public int resetPassword(List<String> ids) {
        int rows = 0;
        if (CollectionUtils.isEmpty(ids)){
            throw new BusinessException("请选择需要重置密码的用户！");
        }
        List<SysUser> users = listByPKs(ids);
        for (SysUser user : users){
            sysUserDao.resetPassword(user.getId(),PwdUtils.md5Encode("123456",user.getLoginName()));
            rows++;
        }

        return rows;
    }

    @Override
    public List<SysUser> listByRole(String roleId) {
        return sysUserDao.listByRole(roleId);
    }

    @Override
    public SysUser validByLoginName(String id, String loginName) {
        return sysUserDao.validByLoginName(id,loginName);
    }

    @Override
    public SysUser validByEmail(String id, String email) {
        return sysUserDao.validByEmail(id,email);
    }

    @Override
    public SysUser validByPhone(String id, String phone) {
        return sysUserDao.validByPhone(id,phone);
    }

    @Override
    public int modifyPassword(SysUser entity) {
        entity.setPassword(PwdUtils.md5Encode(entity.getPassword(),entity.getLoginName()));
        entity.setLoginName(null);
        return update(entity);
    }

    @Override
    public int modifyEnabled(String enable, List<String> ids) {
        return sysUserDao.modifyEnabled(enable,ids);
    }

    @Override
    public int upload(InputStream stream) {
        int rows = 0;
        try {
            List<SysUser> users = ExcelUtils.importExcel(stream,SysUser.class,new String[]{"loginName",
                    "no","name","email","phone"});
            if (CollectionUtils.isNotEmpty(users)){
                for (SysUser entity : users){
                    rows += this.save(entity);
                }

            }
            return rows;
        } catch (Exception e) {
            throw new BusinessException("导入用户错误："+e.getMessage());
        }
    }

    @Override
    public void downloadTemplate(SysUser entity, HttpServletResponse response) {
        try {
            ExcelUtils.exportExcel(response, new BaseExcel() {
                @Override
                public String fileName() {
                    return "用户模板";
                }

                @Override
                public LinkedHashMap<String, String> headers() {
                    LinkedHashMap<String,String> headers = new LinkedHashMap<String, String>();
                    headers.put("loginName","用户名");
                    headers.put("no","工号");
                    headers.put("name","用户姓名");
                    headers.put("email","邮件");
                    headers.put("phone","联系方式");
                    return headers;
                }

                @Override
                public List<Map<String, Object>> datas() {
                    SysUser user = new SysUser();
                    user.setLoginName("whli");
                    user.setEmail("914164909@qq.com");
                    user.setPhone("13000000000");
                    List<SysUser> lines = new ArrayList<SysUser>();
                    lines.add(user);
                    return JacksonUtils.jsonToPojo(JacksonUtils.pojoToJsonIgnoreNull(lines),List.class);
                }
            });
        } catch (Exception e) {
            throw new BusinessException("导出用户模板错误："+e.getMessage());
        }
    }

    @Override
    public void download(SysUser entity, HttpServletResponse response) {

    }
}
